﻿var ns = namespace("kaskelot.web");

ns.formutils = function () {

    function getBlankett(selector) {

        var blankett = {}

        var faltData = new Array();

        $(selector + " :input[id]").each(function () {

            if ($(this).is("[type='button']"))
                return;

            var falt = {};
            falt["Id"] = $(this).data("id");
            
            var data = new Array();

            if ($(this).is("[type='checkbox']")) {
                if ($(this).is(":checked")) {
                    data.push($(this).data("option"));
                    falt["Data"] = data;
                    faltData.push(falt);
                }
            }
            else if ($(this).is("[type='radio']")) {
                if ($(this).is(":checked")) {
                    data.push($(this).data("option"));
                    falt["Data"] = data;
                    faltData.push(falt);
                }
            }
            else {
                data.push($(this).val() != null ? $(this).val() : []);
                falt["Data"] = data;
                faltData.push(falt);
            }
        });

        blankett["Id"] = $(selector).data("blankettid");
        blankett["FaltData"] = faltData;

        return blankett;
    }

    function getObject(selector) {
    	var obj = {};

    	$(selector + " :input[id]").each(function () {
    	    if ($(this).is("[type='button']"))
    	        return;
    	    if ($(this).is("[type='checkbox']")) {
    	        var checkedOnes = obj[$(this).data("field")];
    	        if (!checkedOnes)
    	            checkedOnes = new Array();
    	        if ($(this).is(":checked"))
    	            checkedOnes.push($(this).data("option"));
    	        obj[$(this).data("field")] = checkedOnes;
    	    }
    		else
    			obj[$(this).data("field")] = $(this).val() != null ? $(this).val() : [];
    	});

    	return obj;
    }

    function initSelect(selector) {
        jQuery(selector).chosen({
            "disable_search": true
        }).change(function () {
            $(selector).valid();
        });
    }

    return {
        initSelect: initSelect,
        getObject: getObject,
        getBlankett: getBlankett
        //showError: showError,
    }
}();